package com.lele.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

// 过滤器链
@WebFilter(urlPatterns = "*.one", initParams = {@WebInitParam(name = "encoding", value = "UTF-8")})
public class Filter_A implements Filter {

    private String encoding = "UTF-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 可以在过滤器链里设置编码，这样后面就不用设置了
        // Filter_A ——> Filter_B ——> Filter_C 用注解的话按照字母排序执行，如果是xml配置就按上下顺序（看控制台打印顺序）
        // Listeners ——> Filters ——> DispatcherServlet ——> Controller ——> Service ——> Dao 业务执行总顺序
        String encodingStr = filterConfig.getInitParameter("encoding");
        if (encodingStr != null){
            encoding = encodingStr;
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ((HttpServletRequest)servletRequest).setCharacterEncoding(encoding); // 这里记得强转一下
        System.out.println("请求A1");
        filterChain.doFilter(servletRequest,servletResponse); // 放行
        System.out.println("响应A2");
    }

    @Override
    public void destroy() {
        // 销毁的方法
    }
}
